import { ref, onUnmounted } from 'vue';

export default class WebSocketService {
  constructor(url) {
    this.url = url;
    this.socketTask = null;
    this.socketOpen = false;
    this.messageCallbacks = [];
    this.openCallbacks = [];
    this.closeCallbacks = [];
    this.errorCallbacks = [];
    this.reconnectInterval = 2000; // 重连间隔
    this.reconnectTimer = null;
    this.heartbeatInterval = null; // 心跳间隔
  }

  // 初始化 WebSocket 连接
  init() {
    this.connect();
    this.setupEventHandlers();
  }

  // 创建 WebSocket 连接
  connect() {
    this.socketTask = uni.connectSocket({
      url: this.url,
      success: () => {
        console.log('WebSocket连接已创建!');
      }
    });
  }

  // 设置事件处理程序
  setupEventHandlers() {
    // 监听连接打开事件
    this.socketTask.onOpen((res) => {
      this.socketOpen = true;
      console.log('WebSocket连接已打开');
      this.startHeartbeat(); // 开始心跳
      this.openCallbacks.forEach(callback => callback(res));
    });

    // 监听连接关闭事件
    this.socketTask.onClose((res) => {
      this.socketOpen = false;
      console.log('WebSocket连接已关闭1');
      this.closeCallbacks.forEach(callback => callback(res));
      this.stopHeartbeat(); // 停止心跳
      // this.reconnect();
    });

    // 监听错误事件
    this.socketTask.onError((res) => {
      console.error('WebSocket连接错误', res);
      this.errorCallbacks.forEach(callback => callback(res));
      this.stopHeartbeat(); // 停止心跳
      this.reconnect();
    });

    // 监听消息事件
    this.socketTask.onMessage((res) => {
      console.log('收到消息', res.data);
      if (res.data === '令牌解析异常，即将断开连接！！！') {
        console.log('跳转登录')
        uni.navigateTo({
					url: '/pages/login/index'
				})
        return;
      }
      this.messageCallbacks.forEach(callback => callback(res.data));
    });
  }

  // 发送消息
  sendMessage(data) {
    if (this.socketOpen && this.socketTask) {
      this.socketTask.send({
        data: JSON.stringify(data),
        success: () => {
          console.log('消息发送成功');
        },
        fail: (err) => {
          console.error('消息发送失败', err);
        }
      });
    } else {
      console.error('WebSocket连接未建立，无法发送消息');
    }
  }

  // 关闭连接
  close() {
    if (this.socketTask) {
      this.socketTask.close();
      this.socketTask = null;
    }
    this.clearReconnectTimer();
  }

  // 重连机制
  reconnect() {
    this.clearReconnectTimer();
    this.reconnectTimer = setTimeout(() => {
      this.init();
    }, this.reconnectInterval);
  }

  // 清除重连计时器
  clearReconnectTimer() {
    if (this.reconnectTimer) {
      clearTimeout(this.reconnectTimer);
      this.reconnectTimer = null;
    }
  }

  startHeartbeat() {
    this.heartbeatInterval = setInterval(() => {
      if (this.socketOpen && this.socketTask) {
        console.log('要开始心跳')
        const heartbeatMessage = JSON.stringify({
          "status": "ping",
          "createTime": 0,
          "authentication": uni.getStorageSync('access_token'),
          "channel": "CHANNEL_MOBILE"
        });
        this.socketTask.send({
          data: heartbeatMessage,
          success: () => {
            console.log('心跳已发送');
          },
          fail: (err) => {
            console.error('心跳发送失败', err);
          }
        });
      }
    }, 30000); // 30秒发送一次心跳
  }

  stopHeartbeat() {
    if (this.heartbeatInterval) {
      clearInterval(this.heartbeatInterval);
      this.heartbeatInterval = null;
    }
  }

  // 添加消息回调
  onMessage(callback) {
    this.messageCallbacks.push(callback);
  }

  // 添加连接打开回调
  onOpen(callback) {
    this.openCallbacks.push(callback);
  }

  // 添加连接关闭回调
  onClose(callback) {
    this.closeCallbacks.push(callback);
  }

  // 添加错误回调
  onError(callback) {
    this.errorCallbacks.push(callback);
  }

  // 页面卸载时清理资源
  onDestroy() {
    this.close();
    this.clearReconnectTimer();
    this.messageCallbacks = [];
    this.openCallbacks = [];
    this.closeCallbacks = [];
    this.errorCallbacks = [];
  }
}